package com.sunday.aomicaichang.ui.product;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.ProductDetailRecAdapter;
import com.sunday.aomicaichang.adpter.StringBannerHolder;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.order.CartActivity;
import com.sunday.aomicaichang.ui.widgets.PopProductDetailWindow;
import com.sunday.aomicaichang.widgets.DividerGridItemDecoration;
import com.sunday.aomicaichang.widgets.FlexibleRatingBar;
import com.sunday.aomicaichang.widgets.ShareWindow;
import com.sunday.member.base.BaseFragment;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.RollImage;
import com.sunday.member.entity.product.ProductDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/7.
 */

public class ProductDetailFragment extends BaseFragment {
    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.product_title)
    TextView productTitle;
    @Bind(R.id.btn_share)
    ImageView btnShare;
    @Bind(R.id.product_price)
    TextView productPrice;
    @Bind(R.id.product_old_price)
    TextView productOldPrice;
    @Bind(R.id.btn_a)
    TextView btnA;
    @Bind(R.id.nested_scroll_webview1)
    WebView webView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.img_cart)
    ImageView imgCart;
    @Bind(R.id.add_cart)
    TextView addCart;
    @Bind(R.id.buy_now)
    TextView buyNow;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;
    @Bind(R.id.ly_assess)
    LinearLayout lyAssess;
    @Bind(R.id.ly_assess_parent)
    LinearLayout lyAssessParent;
    @Bind(R.id.btn_collect)
    ImageView btnCollect;
    @Bind(R.id.container)
    LinearLayout container;
    private long productId;
    private ProductDetail productDetail;
    private boolean isCollect=false;
    private long id;

    public static ProductDetailFragment newInstance(long id) {
        ProductDetailFragment fragment = new ProductDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id", id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_product_detail, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getLong("id");
        }
        getProductDetail();
    }

    private void getProductDetail() {
        int villageId = SharePerferenceUtils.getIns(mContext).getInt(com.sunday.aomicaichang.constValues.ConstValue.AREA, 0);
        String nonce = MD5Utils.random();//随机数
        String[] str1 = new String[]{"productId", "villageId", "nonce"};
        String[] str2 = new String[]{String.valueOf(id), String.valueOf(villageId), nonce};
        showLoadingDialog(0);
        Call<ResultDO<ProductDetail>> call = MemberClient.getApiAdapter().getProductDetail(id, villageId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<ProductDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ProductDetail>> call, Response<ResultDO<ProductDetail>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    productDetail = response.body().getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ProductDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        List<String> bannerImgs = new ArrayList<>();
        if (productDetail.getRollImages() != null && !productDetail.getRollImages().isEmpty()) {
            for (RollImage item : productDetail.getRollImages()) {
                if (!TextUtils.isEmpty(item.getUrl())) {
                    bannerImgs.add(item.getUrl());
                }
            }
        }else {
            if (!TextUtils.isEmpty(productDetail.getImage())) {
                bannerImgs.add(productDetail.getImage());
            }
        }
        banner.startTurning(3000);
        banner.setPages(new ViewHolderCreator<StringBannerHolder>() {
            @Override
            public StringBannerHolder createHolder() {
                return new StringBannerHolder();
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();
        if(productDetail.getIsCollection()==0){
            btnCollect.setSelected(false);
            isCollect=false;
        }else {
            btnCollect.setSelected(true);
            isCollect=true;
        }
        productTitle.setText(productDetail.getName());
        productPrice.setText(String.format("￥%s", productDetail.getPrice().setScale(2, RoundingMode.HALF_UP)));
        productOldPrice.setText(String.format("￥%s", productDetail.getMarketPrice().setScale(2, RoundingMode.HALF_UP)));
        productOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        List<ProductDetail.CommentsBean> comments = productDetail.getComments();
        if (comments.size() == 0) {
            lyAssessParent.setVisibility(View.GONE);
        } else {
            lyAssessParent.setVisibility(View.VISIBLE);
            lyAssess.removeAllViews();
            int size = 0;
            if (comments.size() != 0) {
                for (ProductDetail.CommentsBean assess : comments) {
                    size++;
                    View v1 = LayoutInflater.from(mContext).inflate(R.layout.item_goods_assess, null);
                    CircleImageView imgTop = (CircleImageView) v1.findViewById(R.id.img_top);
                    TextView tvName = (TextView) v1.findViewById(R.id.tv_name);
                    FlexibleRatingBar flexibleRatingBar = (FlexibleRatingBar) v1.findViewById(R.id.flexibleRatingBar);
                    TextView tvTime = (TextView) v1.findViewById(R.id.tv_time);
                    TextView asses = (TextView) v1.findViewById(R.id.assess);
                    LinearLayout lyImg = (LinearLayout) v1.findViewById(R.id.ly_img);
                    if (assess.getMemberImage() != null)
                        Picasso.with(mContext)
                                .load(assess.getMemberImage())
                                .error(R.mipmap.ic_avator)
                                .into(imgTop);
                    if (assess.getMemberName() != null)
                        tvName.setText(assess.getMemberName());
                    if (assess.getCreateDateX() != null)
                        tvTime.setText(assess.getCreateDateX());
                    if (assess.getContent() != null)
                        asses.setText(assess.getContent());
                    List<ProductDetail.CommentsBean.ImagesBean> imagesBeen = assess.getImages();
                    lyImg.removeAllViews();
                    if (imagesBeen.size() != 0) {
                        for (ProductDetail.CommentsBean.ImagesBean img : imagesBeen) {
                            View v2 = LayoutInflater.from(mContext).inflate(R.layout.item_assess_img, null);
                            ImageView area = (ImageView) v2.findViewById(R.id.img);
                            if (img.getUrl() != null)
                                Picasso.with(mContext)
                                        .load(img.getUrl())
                                        .error(R.mipmap.ic_product)
                                        .into(area);
                            lyImg.addView(v2);
                        }
                    }
                    flexibleRatingBar.setRating(assess.getScore());
                    lyAssess.addView(v1);
                    if (size ==2)
                        break;
                }
            }
        }

        //启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url)) {
                    view.loadUrl(url);
                } else {
                    dissMissDialog();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dissMissDialog();
            }
        });
        webView.loadUrl(productDetail.getDescUrl());

        if (productDetail.getProducts() != null && !productDetail.getProducts().isEmpty()) {
            ProductDetailRecAdapter adapter = new ProductDetailRecAdapter(mContext, productDetail.getProducts());
            GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position == 0) {
                        return 2;
                    } else {
                        return 1;
                    }
                }
            });

            recyclerView.setLayoutManager(layoutManager);
            recyclerView.addItemDecoration(new DividerGridItemDecoration(5));
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

    }

    private PopProductDetailWindow popBuyWindow;

    @OnClick({R.id.btn_share, R.id.img_cart, R.id.add_cart, R.id.buy_now, R.id.btn_a,R.id.btn_collect})
    void onClick(View v) {
        if (productDetail == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.img_cart:
                intent = new Intent(mContext, CartActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_share:
                if(productDetail.getShareUrl()==null||productDetail.getShareTitle()==null){
                    ToastUtils.showToast(mContext,"数据不完整");
                    return;
                }
                ShareWindow shareWindow=new ShareWindow(mContext,productDetail.getShareUrl(),productDetail.getName(),productDetail.getImage(),productDetail.getShareDesc());
                shareWindow.showPopupWindow(btnShare);
                break;
            case R.id.btn_collect:
                btnCollect.setSelected(!isCollect);
                isCollect = !isCollect;
                collect();
                break;
            case R.id.btn_a:
                intent = new Intent(mContext, ProductActivity.class);
                intent.putExtra("page", 2);
                intent.putExtra("id", id);
                intent.putExtra("name", productDetail.getName());
                startActivity(intent);
                getActivity().finish();
                break;
            case R.id.add_cart:
                if (popBuyWindow == null) {
                    popBuyWindow = new PopProductDetailWindow(mContext, ConstValue.TYPE_ADDCART,
                            productDetail.getImage(), productDetail.getId(), String.format("%s", productDetail.getPrice().setScale(2, RoundingMode.HALF_UP)),
                            productDetail.getSaleNumber());
                } else {
                    popBuyWindow.setBuyType(ConstValue.TYPE_ADDCART);
                }
                popBuyWindow.showPopupWindow(addCart);
                break;
            case R.id.buy_now:
                if (popBuyWindow == null) {
                    popBuyWindow = new PopProductDetailWindow(mContext, ConstValue.TYPE_BUY_NOW, productDetail.getImage(), productDetail.getId(), String.format("%s", productDetail.getPrice().setScale(2, RoundingMode.HALF_UP)),
                            productDetail.getSaleNumber());
                } else {
                    popBuyWindow.setBuyType(ConstValue.TYPE_BUY_NOW);
                }
                popBuyWindow.showPopupWindow(buyNow);
                break;
        }
    }
    private void collect() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"type","otherId", "nonce"};
        String[] str2 = new String[]{String.valueOf(1),String.valueOf(id), nonce};
        Call<ResultDO> call = ApiClient.getApiAdapter().save(1,id, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (isCollect) {
                        ToastUtils.showToast(mContext,"已收藏");
//                        getProductDetail();
                    }else {
                        ToastUtils.showToast(mContext,"已取消收藏");
//                        getProductDetail();
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}

